package ted.test;


import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class GUIThread extends JFrame implements java.awt.event.ActionListener {

    private JButton jb1 = new JButton("计时");
    private JButton jb2 = new JButton("当前时间");
    private JLabel jl1 = new JLabel("");
    private JLabel jl2 = new JLabel("");

    public GUIThread() {
        super("GUIThread");
        this.setSize(300, 200);
        this.setLocation(400, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(2, 2));
        this.jb1.addActionListener(this);
        this.jb2.addActionListener(this);
        this.add(jb1);
        this.add(jl1);
        this.add(jb2);
        this.add(jl2);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new GUIThread();
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        Object jb = e.getSource();
        if (jb == jb1) {
            new TimingTime(jl1).start();
            jb1.setEnabled(false);
        } else {
            new NowTime(jl2).start();
        }
    }
}
class NowTime extends Thread {

    private JLabel jl;

    public NowTime(JLabel jl) {
        this.jl = jl;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Date d = new Date();
            this.jl.setText(d.getYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + "  " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
        }
    }
}

class TimingTime extends Thread {

    private JLabel jl;
    private long l = new Date().getTime();

    public TimingTime(JLabel jl) {
        this.jl = jl;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int emp = 1000;
            int i = (int) ((new Date().getTime() - l) / emp);
            jl.setText(String.valueOf(i));
        }
    }
}
